package com.wpt.sbtest.controller;

import com.wpt.sbtest.domain.Girl;
import com.wpt.sbtest.domain.Result;
import com.wpt.sbtest.repository.GirlRepository;
import com.wpt.sbtest.service.GirlService;
import com.wpt.sbtest.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@RestController
public class GirlController {

    private static final Logger logger = LoggerFactory.getLogger(GirlController.class);

    private final GirlRepository girlRepository;
    private final GirlService girlService;

    @Autowired
    public GirlController(GirlRepository girlRepository, GirlService girlService) {
        this.girlRepository = girlRepository;
        this.girlService = girlService;
    }

    @GetMapping("/girls")
    public List<Girl> girlList(){
        return girlRepository.findAll();
    }
    @PostMapping("/girls")
    public Result addGirl(@Valid Girl girl, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
//            return null;
            return ResultUtil.error(1, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());

        return ResultUtil.success(girlRepository.save(girl));
    }

    @GetMapping(value = "/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id){
        return girlRepository.findById(id).orElse(null);
    }

    /**
     * update girls
     */
    @PutMapping(value = "/girls/{id}")
    public Girl updateGirl(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age){
        Girl girl = new Girl();
        girl.setCupSize(cupSize);
        girl.setAge(age);
        girl.setId(id);
        return girlRepository.save(girl);

    }

    @DeleteMapping(value = "/girls/{id}")
    public void deleteGirl(@PathVariable("id") Integer id){
        girlRepository.deleteById(id);
    }

    @GetMapping("/girls/age/{age}")
    public List<Girl> list(@PathVariable("age") Integer age){
        return girlRepository.findByAge(age);
    }

    @PostMapping("/girls/two")
    public void girlT(){
        girlService.saveTwo();
    }

    @GetMapping("/girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        girlService.getAge(id);
    }
}
